package com.fingard.dsp.bank.directbank.hsbank01;

import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Map;
import java.util.UUID;

/**
 * @author: liuxb
 * @create: 2019-12-19 09:18
 * @version: 1.0
 **/
public class HSBANK01SinglePay extends HSBANK01Base implements ISinglePay {
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT BANKREQSEQID,TRANSDATE FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;";

    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        Connection conn = FGBiz.getLocalDbConn();
        try {
            //赋值通用参数
            HSBANK01Header bankHeader = new HSBANK01Header();
            bankHeader.trCode = "300001";
            bankHeader.reqNo = p_req1908.singleDetail.askNumber;
//            bankHeader.reqNo = p_req1908.reqHeader.reqSeqID;
            bankHeader.fileFlag = "0";//文件标识 0-报文 1-文件
            //写入HSBANK01通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("pay_acno", p_req1908.singleDetail.payAct);//付款账号
            xmlWriter.writeElementString("pay_cur_code", convertCurToBank(p_req1908.singleDetail.payCur));//付款币种
            xmlWriter.writeElementString("pay_acname", p_req1908.singleDetail.payName, true);//付款户名
            xmlWriter.writeElementString("as_flag", "0");//账簿标志 0-不需要 1-需要
            xmlWriter.writeElementString("as_acno", "", true);//账簿号
            xmlWriter.writeElementString("as_acname", "", true);//账簿名称
            xmlWriter.writeElementString("pay_accaddr", "", true);//付款地址
            xmlWriter.writeElementString("cert_type", "", true);//凭证种类
            xmlWriter.writeElementString("cert_no", p_req1908.singleDetail.askNumber);//凭证号(企业账务流水号)
            xmlWriter.writeElementString("rcv_acno", p_req1908.singleDetail.recAct);//收款账号
            xmlWriter.writeElementString("rcv_cur_code", convertCurToBank(p_req1908.singleDetail.recCur));//收款币种
            xmlWriter.writeElementString("rcv_acname", p_req1908.singleDetail.recName, true);//收款户名
            xmlWriter.writeElementString("rcv_accaddr", "", true);//收款人地址
            xmlWriter.writeElementString("rcv_bank_no", p_req1908.singleDetail.cnapsCode);//收款行号，收款方账号联行行号
            xmlWriter.writeElementString("rcv_bank_name", p_req1908.singleDetail.cnapsName, true);//收款行名
            xmlWriter.writeElementString("amt", p_req1908.singleDetail.payAmount);//交易金额
            xmlWriter.writeElementString("bank_flag", "1".equals(p_req1908.singleDetail.sameBnk) ? "0" : "1");//银行标志 0：本行 1：他行
            xmlWriter.writeElementString("urgency_flag", p_req1908.singleDetail.paySpd);//加急标志 0：普通 1：加急
            xmlWriter.writeElementString("area_flag", p_req1908.singleDetail.sameCity);//同城异地标志 0：同城 1：异地
            xmlWriter.writeElementString("bank_kind", "", true);//银行类别
            xmlWriter.writeElementString("purpose", p_req1908.singleDetail.purpose, true);//用途  企业转账摘要信息
            xmlWriter.writeElementString("postscript", "", true);//附言
            xmlWriter.writeElementString("booking_flag", "0");//预约标志 0－是实时交易 1－是预约交易
            xmlWriter.writeElementString("booking_date", "", true);//预约日期
            xmlWriter.writeElementString("booking_time", "", true);//预约时间
            xmlWriter.writeElementString("saverecvinfo_flag", "", true);//是否保存收款方信息
            xmlWriter.writeElementString("mobiles", "", true);//收款方手机号码
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpsuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                    String tmpRespCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/head/ext_info");

                    if (tmpRespCode != null && "0000".equals(tmpRespCode)) {//执行成功
                        //存入银行返回的入账日期，用于查询
                        String transDate = tmpBkReader.getFirstText("/ap/head/tr_acdt");
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req1908.reqHeader.bankCode, transDate, p_req1908.reqHeader.reqSeqID, p_req1908.reqHeader.reqSeqID});
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = StringHelper.joinNotEmpty("+", tmpRetInfo, tmpRetRxtInfo);
                        tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        if ("1".equals(p_req1908.singleDetail.sameBnk) && "0".equals(tmpsuccFlag)) {//同行
                            //跨行的情况：跨行转账时，succ_flag仅表示发送到人行成功，并不代表交易最终状态，最终交易状态需要在交易明细中确认。
                            tmpRetAtsDetail.transState = "5";
                            tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                        } else {
                            //0:成功 8：结果未知 其它：失败
                            tmpRetAtsDetail.transState = "8";
                            tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                        }
                    } else {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.transState = "6";
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                        tmpRetAtsDetail.respInfo = StringHelper.joinNotEmpty("+", tmpRetInfo, tmpRetRxtInfo);
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
        } finally {
            conn.close();
        }

        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    //1944 交易状态查询
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //赋值通用参数
            HSBANK01Header bankHeader = new HSBANK01Header();
            bankHeader.trCode = "200205";
//            bankHeader.reqNo = p_req1944.reqHeader.reqSeqID;
            bankHeader.reqNo = p_req1944.reqHeader.transSeqID;
            bankHeader.fileFlag = "0";//文件标识 0-报文 1-文件
            //写入HSBANK01通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            XElement tmpXElement = new XElement("body", "");
            tmpXElement.addChild(new XElement("cert_no", p_req1944.askNumber));//企业erp[账务]流水号
            tmpXElement.addChild(new XElement("req_no", p_req1944.askNumber));//企业erp［请求］流水号
//            tmpXElement.addChild(new XElement("req_no", bankHeader.reqNo));//企业erp［请求］流水号
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req1944.askNumber, p_req1944.reqHeader.bankCode});
            if (map.size() == 0) {
                tmpRetAtsDetail.respCode = "0";
                tmpRetAtsDetail.respInfo = "没有这条请求映射的流水号,请跟银行线下确认后，手工进行支付结果确认！";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
            tmpXElement.addChild(new XElement("tr_acdt", map.get("TRANSDATE").toString()));
//            tmpXElement.addChild(new XElement("tr_acdt", p_req1944.askNumber));
            tmpXElement.addChild(new XElement("cms_corp_no", ""));//客户号
//            tmpXElement.addChild(new XElement("cms_corp_no", bankFront.corpNo));//客户号
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRespCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/body/error_info");
                    String tmpsuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                    if ("0000".equals(tmpRespCode)) {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        String stat = tmpBkReader.getFirstText("/ap/body/stat");
                        tmpRetAtsDetail.transState = stat;//支付状态码
                        tmpRetAtsDetail.payInfoCode = stat;//支付信息码
                        tmpRetAtsDetail.respInfo = convertRespToBank(stat);//在配置文件中配置交易结果状态（银行返回结果）
                    } else {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        tmpRetAtsDetail.transState = tmpRespCode;
                        tmpRetAtsDetail.payInfoCode = tmpRespCode;
                        tmpRetAtsDetail.respInfo = StringHelper.joinNotEmpty("+", tmpRetInfo, tmpRetRxtInfo);
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
            e.printStackTrace();
        } finally {
            conn.close();
        }

        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    //单笔合批
    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        //返回ATS的对象
//        RetAtsSingleBat retAts = new RetAtsSingleBat(p_req1908BAT);
//        retAts.reqBatchNO = p_req1908BAT.reqBatchNO;
//        retAts.batRespCode = "0";
//        retAts.batTransState = "";
//        retAts.batPayInfoCode = "";
//        while (p_req1908BAT.readRecord()) {
//            ReqPayRecDetail tmpDetail = p_req1908BAT.readedDetail;
//            ReqSingle req1908 = new ReqSingle(p_req1908BAT.reqHeader);
//            req1908.singleDetail = tmpDetail;
//            RetAtsSingle eachRet = d_1908_SglPay(req1908);
//
//            retAts.writeRetDetail(eachRet.retDetail);
//        }
//        retAts.writeAfterDetail();
//        return retAts;
        return null;
    }

    //单笔合批
    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
//        RetAtsSingleBat retAts = new RetAtsSingleBat(p_req1944BAT.reqHeader);
//        retAts.reqBatchNO = p_req1944BAT.reqBatchNO;
//        try {
//            retAts.batRespCode = "0";
//            while (p_req1944BAT.readRecord()) {
//                ReqQrySglBatPayDetail tmpDetail = p_req1944BAT.readedDetail;
//                ReqQrySingle req1944 = new ReqQrySingle(tmpDetail, p_req1944BAT.reqHeader);
//                RetAtsSingle resp1944 = d_1944_QrySglPay(req1944);
//                retAts.writeRetDetail(resp1944.retDetail);
//            }
//        } catch (Exception ex) {
//            WriteBankLogLn(ex);
//            retAts = new RetAtsSingleBat(p_req1944BAT.reqHeader);
//            retAts.batRespCode = "-1";
//            retAts.batRespInfo = ex.getMessage();
//        }
//
//        retAts.writeAfterDetail();
//        return retAts;
        return null;

    }
}
